package com.gxkj.drm.uitls;

import com.alibaba.fastjson.JSON;
import com.gxkj.drm.constant.Constant;
import com.gxkj.drm.dto.CodeMsg;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 发送短信工具类
 */
public class MessageSmsUtil {

    private static final Logger logger = LoggerFactory.getLogger(MessageSmsUtil.class);

    /**
     * 短信发送接口
     * @param mobile 短信接收手机号
     * @param content 短信内容
     * @return
     */
    public static CodeMsg sendMessage(String mobile, String content) {
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(content)) {
            logger.error("sendNewApiMessage fail mobile={} message={}", mobile, content);
            return CodeMsg.ERROR;
        }
        try {
            long timestamp = System.currentTimeMillis();
            String sha1 = "appkey=" + Constant.SMS_APP_KEY + "&content=" + content + "&mobile=" + mobile
                    + "&timestamp=" + timestamp + "&appsecret=" + Constant.SMS_APP_SECRET;
            String sign = DigestUtils.md5Hex(sha1).toUpperCase();
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("appkey", Constant.SMS_APP_KEY);
            paramsMap.put("content", content);
            paramsMap.put("mobile", mobile);
            paramsMap.put("timestamp", timestamp);
            paramsMap.put("sign", sign);
            String result = HttpUtil.getIntance().post(Constant.SMS_CONTENT_FORMAT, paramsMap);
            CodeMsg codeMsg = JSON.parseObject(result, CodeMsg.class);
            if (codeMsg.getCode() == 0) {
                logger.info("sendMessage success mobile={} url={} result={}", mobile, Constant.SMS_CONTENT_FORMAT, result);
                return new CodeMsg(CodeMsg.SUCCESS_CODE, "SUCCESS");
            } else {
                logger.error("sendMessage fail mobile={} url={} result={}", mobile, Constant.SMS_CONTENT_FORMAT, result);
                return new CodeMsg(CodeMsg.ERROR_CODE, "ERROR");
            }
        } catch (Exception e) {
            logger.error("sendMessage fail mobile={} result={}", mobile, e.getMessage());
            return new CodeMsg(CodeMsg.ERROR_CODE, "ERROR");
        }
    }
}
